package com.example.work4.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.example.work4.BR
import com.example.work4.R
import com.example.work4.adapter.viewHolder.MessageViewHolder
import com.example.work4.common.ImageUtil
import com.example.work4.po.Message
import com.example.work4.po.SSOInfo

class MessageListAdapter(var data: ArrayList<Message> = ArrayList(), var avatar:String = ""): RecyclerView.Adapter<MessageViewHolder>() {
    var context: Context? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
        context = parent.context
        return MessageViewHolder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent?.context),
                viewType,
                parent,
                false
            )
        )
    }

    override fun getItemViewType(position: Int): Int {
        if(data[position].sender == SSOInfo.id)
        {
            return R.layout.item_message_me
        }
        return R.layout.item_message_u
    }

    override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
        val binding : ViewDataBinding = holder.dataBinding
        holder.mess = data[position]
        val imgUtil = ImageUtil(context!!)
        if(data[position].sender == SSOInfo.id) {
            imgUtil.GlideLoadCenterCrop(SSOInfo.avatar!!, holder.avatar)
        } else {
            imgUtil.GlideLoadCenterCrop(avatar, holder.avatar)
        }
        binding.setVariable(BR.mess, data[position])
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun update(){
        this.notifyDataSetChanged()
    }

}